<template>
  <div>
    <h1>Elementplus</h1>
    <div>
      <el-card style="max-width: 900px">
        <template #header>
          <div class="card-header">
            <div>
              <span>会员管理</span><br>
              <el-button type="success" plain @click="dialogFormVisible = true">添加会员</el-button>
              <el-button type="primary">导出Excel</el-button>
              <el-button type="danger" @click="batchDelete">批量删除</el-button>
            </div>
          </div>
        </template>
        <!-- 显示会员信息的表格 -->
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="用户名"></el-table-column>
          <el-table-column prop="password" label="密码"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
        </el-table>
        <template #footer>
          <!-- 分页 -->
          <el-pagination
            @current-change="docurrentchange"
            background
            layout="prev, pager, next"
            :total="tableData.length"
            :page-size="5"
          />
        </template>
      </el-card>
      <!-- 添加会员 -->
      <div id="">
        <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
          <el-form :model="form">
            <el-form-item label="ID" :label-width="formLabelWidth">
              <el-input v-model="form.id" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
              <el-input v-model="form.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth">
              <el-input v-model="form.email" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">Cancel</el-button>
              <el-button type="primary" @click="addMember">
                Confirm
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { ElMessage } from 'element-plus';

onMounted(() => {
  query()
})

// 存储会员数据
const tableData = ref<any[]>([]);
const query = () => {
  fetch("http://localhost:3000/users").then((res) => res.json()).then(data => {
    tableData.value = data
  })
}

// 控制添加会员对话框的显示与隐藏
const dialogFormVisible = ref(false);
// 表单标签宽度
const formLabelWidth = '140px';
// 表单数据
const form = reactive({
  id: '',
  name: '',
  password: '',
  email: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
});

// 存储用户选择的会员
const multipleSelection = ref<any[]>([]);

// 处理表格选择变化事件
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

// 分页数据改变触发
const docurrentchange = (number: number) => {
  // 消息提示框
  ElMessage.success("当前页:" + number);
  // 分页显示（这里简单示例，可根据实际需求完善）
  return tableData.value.filter((_, index) => index < 6);
};

// 添加会员方法
const addMember = () => {
  // 验证输入信息是否完整
  if (!form.id || !form.name || !form.password || !form.email) {
    ElMessage.warning('请填写完整的会员信息');
    return;
  }
  // 发送 POST 请求到后端
  fetch('http://localhost:3000/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      id: form.id,
      name: form.name,
      password: form.password,
      email: form.email
    })
  })
  .then(response => response.json())
  .then(newMember => {
    // 将新会员添加到 tableData 中
    tableData.value.push(newMember);
    // 清空表单数据
    form.id = '';
    form.name = '';
    form.password = '';
    form.email = '';
    // 关闭对话框
    dialogFormVisible.value = false;
    ElMessage.success('会员添加成功');
  })
  .catch(error => {
    ElMessage.error('会员添加失败');
    console.error('Error adding member:', error);
  });
};

// 批量删除方法
const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的会员');
    return;
  }
  const idsToDelete = multipleSelection.value.map(item => item.id);
  // 发送删除请求到后端
  idsToDelete.forEach(id => {
    fetch(`http://localhost:3000/users/${id}`, {
      method: 'DELETE'
    }).then(() => {
      // 从 tableData 中移除已删除的会员
      tableData.value = tableData.value.filter(item => item.id !== id);
      ElMessage.success('会员删除成功');
    }).catch(() => {
      ElMessage.error('会员删除失败');
    });
  });
  // 清空选择
  multipleSelection.value = [];
};
</script>

<style scoped>
.a1 {
  color: #1fd3a6;
}
.a2 {
  color: blue;
}
</style>